<template>
  <div class="category-container">
    <!-- 搜索框粘性定位 -->
    <van-sticky>
      <van-search placeholder="搜索商品名称" />
    </van-sticky>
    <!-- 分类商品 -->
    <div class="box">
      <!-- 分类区域 -->
      <van-sidebar v-model="active">
        <van-sidebar-item
          v-for="category in categorys"
          :key="category.id"
          :title="category.title"
          @click="clickCategory($event, category.id)"
        />
      </van-sidebar>
      <!-- 分类对应商品区 -->
      <div class="content">
        <div class="imgwrap" v-if="category.img_url">
          <van-image width="255" height="76" :src="category.img_url" />
        </div>

        <div class="goodslist">
          <van-card
            v-for="item in goods"
            :price="item.sell_price + '.00'"
            :key="item.id"
            :title="item.title"
            :origin-price="item.market_price"
            :thumb="item.thumb_path"
            @click="$router.push('/goodsDetail/' + item.id)"
          />
        </div>
        <van-empty v-if="goods.length === 0" description="暂无商品" />
      </div>
    </div>
  </div>
</template>

<script>
import { reqCategory, reqCategoryGoods } from '@/api'
export default {
  data() {
    return {
      active: 0,
      categorys: [],
      category: {},
      goods: [],
    }
  },
  methods: {
    clickCategory(index, category_id) {
      // 防止点击同一个分类多次
      if (this.category.id === category_id) {
        return
      }

      // 获取对应的分类数据赋值给this.category
      this.category = this.categorys[index]
      // 获取当前分类下面的商品
      this.getCategoryGoods()
    },
    async getCategory() {
      let categorys = await reqCategory()
      this.categorys = categorys
      this.category = categorys[0]
    },
    async getCategoryGoods() {
      let goods = await reqCategoryGoods(this.category.id)
      this.goods = goods
    },
  },
  async mounted() {
    await this.getCategory()
    this.getCategoryGoods()
  },
}
</script>

<style lang="scss" scoped>
.category-container {
  .box {
    display: flex;
    justify-content: space-between;

    .van-sidebar {
      height: 100vh;
    }

    .content {
      flex: 1;
      height: 100vh;
      overflow: auto;

      .imgwrap {
        display: flex;
        justify-content: center;
      }

      .goodslist {
        .van-card {
          background-color: #fff;

          .van-card__price {
            color: #ff6000;
          }
        }
      }
    }
  }
}
</style>
